﻿//USER GRID SPECIFIC LOGIC

var saveUser, getUser;

var ajaxUrl = {
    getUserProfileURL: "/Service/Services.aspx/UserProfile",
    updateUserProfileURL : "/Service/Services.aspx/UpdateUserProfile",
};

$(document).ready(function () {

    //PRIVATE VARIABLES    
    var intrnl = false;
    var isloaded = false;
    var sel_row;
    var gridRow;
    var grid = jQuery("#list");
    var glasswrapper = $('#glasswrapper');
    var overridepage = 0; //i need this for the resize column functionality.
    var hashpassword = $('.hidPass').val();
    var hashfull = $('.hidHash').val();

    $('#passwordchanger').dialog({ autoOpen: false, minWidth: 475, minHeight: 240, resizable: false, close: function (event, ui) { glasswrapper.hide(); } });

    //EVENTS
    $('.detailcancel').click(function () {
        preSave();
        getUser();
        return false;
    });
    $('.detailsave').click(function () {
        saveUser();
        return false;
    });
    $('#up_ChangePass').click(function () {
        glasswrapper.show();
        $('#passwordchanger').dialog('open');
        return false;
    });
    $('#btn_changepass_cancel').click(function () {
        $('#passwordchanger').dialog('close');
        $('#changepass_oldpass').val('');
        $('#changepass_newpass1').val('');
        $('#changepass_newpass2').val('');
        $('#passwordchanger').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
        return false;
    });
    $('#btn_changepass_go').click(function () {
        changeIt();
        return false;
    });
    $(".form_table input:checkbox").click(function () {
        promptSave();
    });
    $('.form_table input.form_txt').keydown(function () {
        promptSave();
    });
    $('.form_table input.form_txtarea').keydown(function () {
        promptSave();
    });

    //FORM
    FillUserForm = function (user) {
        $('.detailsave').show();
        $('#user_email').html(user.Email);
        //$('#display_name').html(rowdata.DisplayName);
        $('#user_firstname').val(user.FirstName);
        $('#user_lastname').val(user.LastName);
        //$('#user_organization').val(rowdata.Organization);
        $('#user_role').html(user.ClientRoleName);
        $('#user_title').val(user.Title);
        $('#user_phone1').val(user.Phone1);
        $('#user_phone2').val(user.Phone2);
        $('#user_address1').val(user.Address1);
        $('#user_address2').val(user.Address2);
        $('#user_city').val(user.City);
        $('#user_zipcode').val(user.PostalCode);
        $('#user_state').val(user.StateProv);
        $('#user_country').val(user.Country);
        preSave();
    };

    FillGridRowClass = function () {
        var isvalid = true;
        var gridRow = new Object();
        gridRow.Email = $('#user_email').html();
        gridRow.ClientRoleName = $('#user_role').html();
        gridRow.FirstName = $('#user_firstname').val();
        gridRow.LastName = $('#user_lastname').val();
        gridRow.Title = $('#user_title').val();
        gridRow.Phone1 = $('#user_phone1').val();
        gridRow.Phone2 = $('#user_phone2').val();
        gridRow.Address1 = $('#user_address1').val();
        gridRow.Address2 = $('#user_address2').val();
        gridRow.City = $('#user_city').val();
        gridRow.PostalCode = $('#user_zipcode').val();
        gridRow.StateProv = $('#user_state').val();
        gridRow.Country = $('#user_country').val();
        //validation
        if (gridRow.FirstName.length < 1) {
            isvalid = false;
        }
        if (gridRow.LastName.length < 1) {
            isvalid = false;
        }
        if (gridRow.Phone1.length < 1) {
            isvalid = false;
        }
        if (!isvalid) {
            gridRow.valid = false;
        }
        return gridRow;
    };

    //Methods
    getUser = function () {
        $('#loaderwrapper').show();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: ajaxUrl.getUserProfileURL,
            data: '',
            dataType: "json",
            success: function (data, textStatus) {
                if (textStatus == "success") {
                    var userdata = jQuery.parseJSON(data.d);
                    FillUserForm(userdata);
                    $('#loaderwrapper').hide();
                }
            },
            error: function (data, textStatus) {
                $('#loaderwrapper').hide();
            }
        });
    };

    saveUser = function () {
        var keepgoing = false
        gridRow = FillGridRowClass();
        var frmvisualvalid = false;
        frmvisualvalid = $('#frmuserprofile').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
        if (frmvisualvalid) {
            if (gridRow.valid == null) {
                var params = '{json:' + JSON.stringify(gridRow) + '}';
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: ajaxUrl.updateUserProfileURL,
                    data: params,
                    dataType: "json",
                    success: function (data, textStatus) {
                        if (textStatus == "success") {
                            $('#loaderwrapper').show();
                            //FillUserForm(gridRow);
                            preSave();
                            $('#loaderwrapper').hide();
                            //CancelClick();
                            alert('Your Profile was successfully updated!');
                        }
                    },
                    error: function (data, textStatus) {
                        alert('An error has occured retrieving data!');
                    }
                });
                keepgoing = true;
            }
        }
        if (!keepgoing) {
            alert("CHECK FIELDS HIGHLIGHTED IN RED:\n\nThere are missing or invalid values given.  please correct the identified fields, and re-submit.");
        }
    };

    changeIt = function () {
        var frmvisualvalid = false;
        frmvisualvalid = $('#passwordchanger').jVal({ style: 'blank', padding: 8, border: 0, wrap: false });
        if (frmvisualvalid) {
            //update password and close dialog
            var login = $('#user_email').html();
            var oldpassword = $('#changepass_oldpass').val();
            var newpassword = $('#changepass_newpass1').val();
            var secret = $('.hidSecret').val();
            var hashpass = "";
            var hashnewpass = "";
            var fullprehash = "";
            if (oldpassword.length <= 0) {
                alert('Please enter your current password');
                return false;
            } else if (secret.length <= 0) {
                alert('Error: Unable to generate secret. Please close this browser and try again');
                return false;
            } else {
                hashpass = hex_md5(oldpassword).toLowerCase();
                hashnewpass = hex_md5(newpassword).toLowerCase();
                $('.hidOldPass').val(hashpass);
                $('.hidNewPass').val(hashnewpass);
                fullprehash = hex_md5(login + hashpass + secret).toLowerCase();
                $('.hidHash').val(fullprehash);
            }
            var paramstring = "{fh:'" + fullprehash + "', np:'" + hashnewpass + "',secret:'" + secret + "'}";
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Service/Services.aspx/ChangePassword",
                data: paramstring,
                dataType: "json",
                success: function (data, textStatus) {
                    var msg = jQuery.parseJSON(data.d);
                    if (msg.ReturnCode == 0) {
                        $('#changepass_oldpass').val('');
                        $('#changepass_newpass1').val('');
                        $('#changepass_newpass2').val('');
                        $('.hidOldPass').val('');
                        $('.hidNewPass').val('');
                        $('.hidHash').val('');
                        $('#passwordchanger').dialog('close');
                        $('#passwordchanger').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
                        alert('Your Password has been changed.');
                    } else {
                        alert(msg.Message);
                    }
                },
                error: function (data, textStatus) {
                    //alert('An error has occured retrieving data!');
                }
            });
        }
    };

    promptSave = function () {
        //$('').attr('disabled', true);
        $('.detailsave').button("option", "disabled", false);
        $('.detailcancel').button("option", "disabled", false);
    };
    
    preSave = function() {
        $('.detailcancel').button("option", "disabled", true);
        $('.detailsave').button("option", "disabled", true);
        frmvisualvalid = $('#frmuserprofile').jVal({ style: 'cover', padding: 3, border: 1, wrap: true });
        $('#frmuserprofile').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
        $('#passwordchanger').stop().find('.jfVal,.jValCover').stop().remove().end().find('.jVal,[jVal]').css({ position: '', borderColor: '', left: '0px', top: '0px' }).parent().find('.jValRelWrap').remove();
    };
    
    getUser();
});


